package com.uphone.kingmall.utils;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.china.zhuoyue.R;
import com.uphone.kingmall.activity.personal.set.ModifyPayPwdBackActivty;
import com.uphone.kingmall.activity.personal.set.ModifyPayPwdSetActivty;
import com.uphone.kingmall.view.dialog.OnDialogViewClickListener;
import com.uphone.kingmall.view.dialog.RadishDialog;

/**
 * @ 创建时间: 2017/12/1 on 8:29.
 * @ 描述：对话框工具类
 */

public class DialogUtil {
    private static DisplayMetrics displayMetrics;

    /**
     * 提示等待窗口
     */
    public static Dialog showLoadingDialog(Activity activity, String remind) {
        // 获取Dialog布局
        View view = LayoutInflater.from(activity).inflate(R.layout.kingmall_common_dialog_loading, null);
        // 获取自定义Dialog布局中的控件
        LinearLayout bg = view.findViewById(R.id.LoadingBackground);//跟布局
        TextView title = view.findViewById(R.id.LoadingText);//标题

        if (!TextUtils.isEmpty(remind)) {
            title.setText(remind);
        }

        // 定义Dialog布局和参数
        final Dialog dialog = new Dialog(activity, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);
        // 调整dialog背景大小
        int width = (int) (getDisplay(activity).widthPixels * 0.5);
        int height = width / 3;
        bg.setLayoutParams(new FrameLayout.LayoutParams(width, height));
        return dialog;
    }

    private static DisplayMetrics getDisplay(Activity activity) {
        if (displayMetrics == null) {
            synchronized (DialogUtil.class) {
                displayMetrics = new DisplayMetrics();
                activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            }
        }
        return displayMetrics;
    }

    /**
     * 拨打电话
     * 仅限 activity 中使用
     *
     * @param context
     * @param phone
     */
    public static void showCallDialog(final Activity context, final String phone) {
        if (TextUtils.isEmpty(phone)) {
            ToastUtils.showShortToast(context, "电话号码有误！");
            return;
        }
        try {
            new RadishDialog.Builder(context).setView(R.layout.kingmall_dialog_alter)
                    .setText(R.id.dialog_message, "拨打电话：" + phone)
                    .setClick(R.id.dialog_submit, new OnDialogViewClickListener() {
                        @Override
                        public void onClick(final RadishDialog dialog, View view) {
                            PermissionsUtils.getInstance().checkPermissions(context, new PermissionsUtils.IPermissionsResult() {
                                @Override
                                public void passPermissions() {
                                    Intent intent = new Intent(Intent.ACTION_CALL);
                                    Uri data = Uri.parse("tel:" + phone);
                                    intent.setData(data);
                                    context.startActivity(intent);
                                }

                                @Override
                                public void refusePermissions() {
                                    openAppDetails(context, "拨打电话");
                                }
                            }, Manifest.permission.CALL_PHONE);
                            dialog.dismiss();
                        }
                    })
                    .setClick(R.id.dialog_cancel, new OnDialogViewClickListener() {
                        @Override
                        public void onClick(RadishDialog dialog, View view) {
                            dialog.dismiss();
                        }
                    }).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开 APP 的详情设置 （ 拒绝权限的时候调用 ）
     */
    public static void openAppDetails(final Context context, String info) {
        CommonUtil.showAlterDialog(context, "无法获取到“" + info + "”权限，请到手机应用权限管理中打开“" + info + "”权限", new CommonUtil.OnAlterDialogCallBack() {
            @Override
            public void callBack(RadishDialog dialog, View view) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.addCategory(Intent.CATEGORY_DEFAULT);
                intent.setData(Uri.parse("package:" + context.getPackageName()));
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                context.startActivity(intent);
                dialog.dismiss();
            }
        });
    }


    public static RadishDialog showDialogWalletPay(final Activity context, final OnWalletPayDialogCallBack callBack) {
        View inflate = View.inflate(context, R.layout.kingmall_dialog_pay_wallet, null);
        final EditText et_psd = inflate.findViewById(R.id.et_psd);
        RadishDialog dialog = new RadishDialog.Builder(context).setView(inflate)
                .setClick(R.id.tv_set_psd, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        CommonUtil.startIntent(context, ModifyPayPwdSetActivty.class);
                    }
                })
                .setClick(R.id.tv_pwd_back, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        CommonUtil.startIntent(context, ModifyPayPwdBackActivty.class);
                    }
                })
                .setClick(R.id.dialog_submit, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(final RadishDialog dialog, View view) {
                        if (CommonUtil.checkViewEmpty("请输入密码", et_psd)) {
                            return;
                        }
                        if (callBack != null) {
                            callBack.callBack(dialog, view, et_psd.getText().toString().trim());
                        }
//                        dialog.dismiss();
                    }
                })
                .setClick(R.id.dialog_cancel, new OnDialogViewClickListener() {
                    @Override
                    public void onClick(RadishDialog dialog, View view) {
                        dialog.dismiss();
                    }
                })
                .setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                et_psd.clearFocus();
                                KeyboardUtils.hideSoftInput(et_psd);
                                KeyboardUtils.hideSoftInput(context);
                            }
                        }, 200);
                    }
                })
                .show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(200);
                context.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        et_psd.setFocusable(true);
                        KeyboardUtils.showSoftInput(et_psd);
                    }
                });

            }
        }).start();
        return dialog;

    }

    public static void showShareDailog(Activity activity, String title, String content, String
            dialogTitle) {
        LogUtils.e("分享内容:" + content);
        Intent share_intent = new Intent();
        share_intent.setAction(Intent.ACTION_SEND);//设置分享行为
        share_intent.setType("text/plain");// 设置分享内容的类型
        share_intent.putExtra(Intent.EXTRA_SUBJECT, title);//添加分享内容标题
        share_intent.putExtra(Intent.EXTRA_TEXT, content);//添加分享内容
        //创建分享的Dialog
        share_intent = Intent.createChooser(share_intent, dialogTitle);
        activity.startActivity(share_intent);
    }


    public interface OnWalletPayDialogCallBack {
        void callBack(RadishDialog dialog, View view, String psd);
    }

    /**
     * 设置对话框的宽度和高度,需要在show()之后调用
     *
     * @param widPer 宽度百分比
     * @param heiPer 高度百分比
     */
    public static void setDialogWidAndHei(Dialog dialog, float widPer, float heiPer, Activity activity) {
        if (!activity.isFinishing() && !activity.isDestroyed()) {
            WindowManager windowManager = activity.getWindowManager();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            windowManager.getDefaultDisplay().getMetrics(displayMetrics);
            Window window = dialog.getWindow();
            if (window != null) {
                WindowManager.LayoutParams dialogAttributes = window.getAttributes();
                dialogAttributes.width = (int) (displayMetrics.widthPixels * widPer);
                dialogAttributes.height = (int) (displayMetrics.heightPixels * heiPer);
                window.setAttributes(dialogAttributes);
            }
        }
    }

    /**
     * 设置对话框的宽度,需要在show()之后调用
     *
     * @param widPer 宽度百分比
     */
    public static void setDialogWidth(Dialog dialog, float widPer, Activity activity) {
        WindowManager windowManager = activity.getWindowManager();
        DisplayMetrics displayMetrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(displayMetrics);
        Window window = dialog.getWindow();
        if (window != null) {
            WindowManager.LayoutParams dialogAttributes = window.getAttributes();
            dialogAttributes.width = (int) (displayMetrics.widthPixels * widPer);
            window.setAttributes(dialogAttributes);
        }
    }


    /**
     * @param layoutBg  根部局背景
     * @param title     标题
     * @param msg       消息
     * @param cancel    取消
     * @param confirm   确认
     * @param canCancel 能否取消
     */
    public static Dialog showMsgDialog(Activity activity, int layoutBg, String title, String msg, String cancel, String confirm, int gravity, boolean canCancel, final OnConfirmButtonClick buttonClick) {
        // 获取Dialog布局
        View view = LayoutInflater.from(activity).inflate(
                R.layout.kingmall_common_dialog_alert, null);
        // 获取自定义Dialog布局中的控件
        LinearLayout llBg = view.findViewById(R.id.lLayout_bg);//跟布局
        TextView tvTitle = view.findViewById(R.id.tvTitle);//标题
        TextView tvMsg = view.findViewById(R.id.tvMsg);//提示信息
        TextView btnCancel = view.findViewById(R.id.tvCancel);//取消按钮
        TextView btnSubmit = view.findViewById(R.id.tvSubmit);//确定按钮
        View ivLine = view.findViewById(R.id.ivLine);//中间线

        // 定义Dialog布局和参数
        final Dialog dialog = new Dialog(activity, R.style.AlertDialogStyle);
        dialog.setContentView(view);
        if (layoutBg != 0) {
            llBg.setBackgroundResource(layoutBg);
        }
        if (TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.INVISIBLE);
        } else {
            tvTitle.setText(title);
        }
        if (TextUtils.isEmpty(msg)) {
            tvMsg.setVisibility(View.GONE);
        } else {
            tvMsg.setText(msg);
            if (gravity != -1) {
                tvMsg.setGravity(gravity);
            } else {
                tvMsg.setGravity(Gravity.CENTER);
            }

        }
        if (TextUtils.isEmpty(cancel)) {
            btnCancel.setVisibility(View.GONE);
            ivLine.setVisibility(View.GONE);
        } else {
            btnCancel.setText(cancel);
        }
        if (TextUtils.isEmpty(confirm)) {
            btnSubmit.setVisibility(View.GONE);
            ivLine.setVisibility(View.GONE);
        } else {
            btnSubmit.setText(confirm);
        }
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        btnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (buttonClick != null) {
                    buttonClick.onConfirmButtonClick(dialog, "");
                }
            }
        });
        dialog.setCanceledOnTouchOutside(canCancel);
        dialog.show();
        //对话框宽度为屏幕四分之三
        setDialogWidth(dialog, 0.75f, activity);
        return dialog;
    }

    public interface OnConfirmButtonClick {
        void onConfirmButtonClick(Dialog dialog, String inputText);
    }
}